package com.project.study.farming.common.handle;

import com.alibaba.fastjson.JSON;
import com.project.study.farming.common.entity.dto.BaseOutDto;
import com.project.study.farming.common.exception.ServiceException;
import com.project.study.farming.common.utils.CommonUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

/**
 * 全局异常处理类
 * @since 2020-04-15
 */
@Component
@ControllerAdvice
public class HandleException {

    @ExceptionHandler(Exception.class)
    public ModelAndView systemError(Exception e){
        return this.getModelAndView(e);
    }

    @ExceptionHandler(RuntimeException.class)
    public ModelAndView runtimeError(RuntimeException e){
        return this.getModelAndView(e);
    }

    @ExceptionHandler(ServiceException.class)
    public ModelAndView serviceError(ServiceException e){
        return this.getModelAndView(e);
    }

    private ModelAndView getModelAndView(Exception e){
        return CommonUtil.success("alert.html", e.getMessage());
    }

    private String getRes(Exception e){
        return JSON.toJSONString(BaseOutDto.success(e.getMessage()));
    }
}
